package com.djl.zenithbite.interceptor;

import com.djl.zenithbite.common.threadlocal.UserContextHolder;
import com.djl.zenithbite.entity.LoginCredentials;
import com.djl.zenithbite.entity.User;
import com.djl.zenithbite.entity.UserExample;
import com.djl.zenithbite.repository.UserMapper;
import com.djl.zenithbite.service.user.UserCredentialsService;
import com.djl.zenithbite.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserCredentialsService userCredentialsService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtil.getValue(request, "token");
        if (UserContextHolder.getUser() != null) {
            return true;
        }
        if (ticket != null) {
            LoginCredentials loginCredentials = userCredentialsService.findLoginCredentials(ticket);
            if (loginCredentials != null && loginCredentials.getStatus() == 0) {
                UserExample userExample = new UserExample();
                UserExample.Criteria criteria = userExample.createCriteria();
                criteria.andUserIdEqualTo(loginCredentials.getUserId());
                User loginUser = userMapper.selectByExample(userExample).get(0);
                UserContextHolder.init(loginUser);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.clear();
    }
}
